package net.skyplabs.android.tvrc;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class BtInterface {
	
	private static final String BT_NAME = "SkypDevice";
	private static final String BT_UUID = "00001101-0000-1000-8000-00805F9B34FB";

	private BluetoothDevice device = null;
	private BluetoothSocket socket = null;
	private InputStream receiveStream = null;
	private OutputStream sendStream = null;
	
	private ReceiverThread receiverThread;

	private Handler handlerStatus;

	public BtInterface(Handler hstatus, Handler hmessage)
	{
		Set<BluetoothDevice> setpairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
		BluetoothDevice[] pairedDevices = (BluetoothDevice[]) setpairedDevices.toArray(new BluetoothDevice[setpairedDevices.size()]);
		
		for (int i=0; i<pairedDevices.length; i++)
		{
			if (pairedDevices[i].getName().contains(BT_NAME))
			{
				device = pairedDevices[i];
				
				try
				{
					socket = device.createRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
					receiveStream = socket.getInputStream();
					sendStream = socket.getOutputStream();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				
				break;
			}
		}

		handlerStatus = hstatus;
		
		receiverThread = new ReceiverThread(hmessage);
	}
	
	public void sendData(String data)
	{
		sendData(data, false);
	}
	
	public void sendData(String data, boolean deleteScheduledData)
	{
		try
		{
			sendStream.write(data.getBytes());
	        sendStream.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void connect()
	{
		new Thread()
		{
			@Override
			public void run()
			{
				try
				{
					if (socket != null)
					{
						socket.connect();
					
						Message msg = handlerStatus.obtainMessage();
						msg.arg1 = 1;
						handlerStatus.sendMessage(msg);
	                
						receiverThread.start();
					}
					else
					{
						Message msg = handlerStatus.obtainMessage();
						msg.arg1 = 2;
						handlerStatus.sendMessage(msg);
					}
				}
				catch (IOException e)
				{
					Log.v("N", "Connection Failed : "+e.getMessage());
					e.printStackTrace();
				}
			}
		}.start();
	}

	public void close()
	{
		try
		{
			receiverThread.stopReceiver();
			socket.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public BluetoothDevice getDevice()
	{
		return device;
	}
	
	private class ReceiverThread extends Thread
	{
		private Handler handler;
		private boolean receiveData = true;
		
		ReceiverThread(Handler h)
		{
			handler = h;
		}
		
		public void stopReceiver()
		{
			receiveData = false;
		}
		
		@Override
		public void run()
		{			
			while (receiveData)
			{
				try
				{
					if (receiveStream.available() > 0)
					{
						byte buffer[] = new byte[100];
						int k = receiveStream.read(buffer, 0, 100);

						if (k > 0)
						{
							byte rawdata[] = new byte[k];
							for(int i=0;i<k;i++)
								rawdata[i] = buffer[i];
							
							String data = new String(rawdata);

							Message msg = handler.obtainMessage();
							Bundle b = new Bundle();
							b.putString("receivedData", data);
			                msg.setData(b);
			                handler.sendMessage(msg);
						}
					}
				} 
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}